import { ChangeDetectionStrategy, ChangeDetectorRef, Component, OnInit, ViewChild } from '@angular/core';
import { FilterItem, PaginatorComponent, TableFilterConfig, TreetableComponent, TreeTableNode } from '@iux/live';
import { TreetableService } from '../tree-table.service';
import { filter as _filter, orderBy as _orderBy } from 'lodash';

@Component({
  selector: 'app-sort-and-filter',
  templateUrl: './sort-and-filter.component.html',
  styles: [
    `
      lv-paginator {
        margin-top: 16px;
      }
    `,
  ],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class SortAndFilterComponent implements OnInit {
  data: TreeTableNode[];
  randomFilters: FilterItem[];
  ageFilters: FilterItem[];
  @ViewChild(TreetableComponent, { static: false }) lvTable: TreetableComponent;
  @ViewChild(PaginatorComponent, { static: false }) lvPaginator: PaginatorComponent;

  constructor(private treeTableService: TreetableService, private cdr: ChangeDetectorRef) {}

  ngOnInit() {
    this.initData();
    this.initAsyncData();
  }

  initData() {
    this.setFilter();
  }

  initAsyncData() {
    this.treeTableService.getUsers().subscribe((res: TreeTableNode[]) => {
      this.data = res;
      this.cdr.markForCheck();
    });
  }

  setFilter() {
    this.randomFilters = [
      {
        key: 0,
        label: 'odd',
        value: false,
        selected: false,
      },
      {
        key: 1,
        label: 'even',
        value: true,
        selected: false,
      },
    ];

    this.ageFilters = [
      {
        key: 0,
        label: '20',
        value: 20,
        selected: false,
      },
      {
        key: 1,
        label: '60',
        value: 60,
        selected: false,
      },
    ];
  }

  filterChange(options: TableFilterConfig) {
    this.lvTable.filter(options);
    this.lvPaginator.jumpToFisrtPage();
  }

  customFilterRandom<T>(data: T[], filterOptions: any): T[] {
    const filterValue = filterOptions.value;
    return _filter(data, item => filterValue.includes(item.data.random % 2 === 0) || !filterValue.length);
  }

  customSortAge<T>(data: T[], sortOptions: any): T[] {
    return _orderBy(data, [sortOptions.key], [sortOptions.direction]);
  }

  stateChange(source: { [key: string]: any }) {
    console.log('state change:', source);
  }
}
